package com.example.androidmaze;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.text.Layout;
import android.util.Log;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.support.v4.app.NavUtils;
import android.support.v4.view.GestureDetectorCompat;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;

public class PlayActivity extends Activity implements android.view.GestureDetector.OnGestureListener, OnDoubleTapListener{
	final Handler mazeHandler = new Handler();
	static boolean mapVisible;
	static boolean isActive;
	Maze maze;
	MazePanel mazeView;
	private static final String TAG = "PlayActivity";
	Singleton mazeInstance = Singleton.getInstance();
	private LinearLayout.LayoutParams params;
	String strOperation;
	final String manualOp = "Manual";
	private GestureDetectorCompat mDetector;
	LinearLayout mainLayout;

	// Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mapVisible = false;
		isActive = true;
		setupActionBar();
		addTouchListener();
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			strOperation = extras.getString("Operation");
		}
		Log.v(TAG, "Operation method: " + strOperation);
		
		//doing things for manual AND robot
		super.onCreate(savedInstanceState);
		
		final LinearLayout mainLayout = new LinearLayout(this);
		params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		mainLayout.setLayoutParams(params);
		mainLayout.setOrientation(LinearLayout.VERTICAL);
		//reads singleton generated maze
		this.maze = mazeInstance.getMaze();
		mazeView = new MazePanel(this);
		params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		mazeView.setLayoutParams(params);
		mainLayout.addView(mazeView);
		Log.v(TAG, "setting content view to layout view");
		setContentView(mainLayout);

		//sets mazeView to maze object
		maze.setMazePanel(mazeView);

		Log.v(TAG, "notifying view redraw in maze object");
		maze.notifyViewerRedraw(); //must do this for maze to draw first
		//end things for manual AND robot
		
		//Robots: 
		//create robot	
		
		if (strOperation.equals("Gambler")) {
			startRobot(strOperation);
		}
		else if (strOperation.equals("Curious Gambler")) {
			startRobot(strOperation);
		}
		else if (strOperation.equals("Wizard")) {
			startRobot(strOperation);
		}
		else if (strOperation.equals("Wall Follower")) {
			startRobot(strOperation);
			}
	}
	
	public void startRobot(String operation) {
		Log.v(TAG, "Creating Robot");
		mazeInstance.setDriver(operation);
		
		
		startRobotInstance();
	}
	
	protected void startRobotInstance() {
		
		// Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
            	mazeInstance.startRobot();
        		maze.notifyViewerRedraw();
//                mResults = doSomethingExpensive();
        		///mazeHandler.post(mUpdateResults);
                mazeHandler.postDelayed(mUpdateResults, 500);
            }
        };
        t.start();
	}
	
	public void updateResultsInUi() {
		//do we need this/mazeView.invalidate();
		// back in UI thread, update UI elements based off data in mResults
	}

	public void toFinish(View view) {
		Intent intent = new Intent(this, FinishActivity.class);
		startActivity(intent);
	}
	
	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.play, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case com.example.androidmaze.R.id.zoom_in:
			if(mapVisible) {
				Log.v(TAG, "ZOOM IN clicked");
				maze.keyDown('+');
			}
			return true;
		case com.example.androidmaze.R.id.zoom_out:
			Log.v(TAG,"ZOOM OUT clicked");
			Log.v(TAG, "mapVisible: " + mapVisible);
			if (mapVisible){
				maze.keyDown('-');
			}
			return true;
		case com.example.androidmaze.R.id.title:
			Log.v(TAG, "TITLE clicked");
			Intent intent = new Intent(this, TitleActivity.class);
			startActivity(intent);
			return true;
		case com.example.androidmaze.R.id.rotate_left:
			Log.v(TAG,"ROTATE LEFT clicked");
			maze.keyDown('l');
			return true;
		case com.example.androidmaze.R.id.forward_step:
			Log.v(TAG,"FORWARD STEP clicked");
			maze.keyDown('f');
			return true;
		case com.example.androidmaze.R.id.backward_step:
			Log.v(TAG,"BACKWARD STEP clicked");
			maze.keyDown('b');
			return true;
		case com.example.androidmaze.R.id.rotate_right:
			Log.v(TAG,"ROTATE RIGHT clicked");
			maze.keyDown('r');
			return true;
		case com.example.androidmaze.R.id.showMap:
			Log.v(TAG,"SHOW MAP clicked");
			mapVisible = !mapVisible;
			maze.keyDown('m');
			return true;
		case com.example.androidmaze.R.id.showSolution:
			Log.v(TAG,"SHOW SOLUTION clicked");
			if (mapVisible) {
				maze.keyDown('s');
			}
			return true;
		case com.example.androidmaze.R.id.mapMode:
			Log.v(TAG, "TOGGLE MAP MODE clicked");
			if (mapVisible) {
				maze.keyDown('n');
			}
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	Intent intent = new Intent(this, TitleActivity.class);
	    	Log.v(TAG, "BACK button pressed");
			Log.v(TAG, "To activity TitleActivity");
			startActivity(intent);
	        return true;
	    }

	    return super.onKeyDown(keyCode, event);
	}

	 public void addTouchListener()
     {
		 Log.v(TAG, "Initiating mDector!!!!!!!!!!!!!!!!!!!!!!!!!");
             this.mDetector = new GestureDetectorCompat(this,this);
             if (mDetector == null) {
            	 Log.e(TAG, "new mDetector is NULL");
             }
             this.mDetector.setOnDoubleTapListener(this);
     }


     @Override
     public boolean onTouchEvent(MotionEvent event){
    	 if (mDetector == null) {
    		 Log.e(TAG, "mDetector == NULL");
    	 }
	     this.mDetector.onTouchEvent(event);
	     return super.onTouchEvent(event);
     }
     
     @Override
     public boolean onDown(MotionEvent e) {
    	 	//maze.keyDown('b');
             return true;
     }


     @Override
     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                     float velocityY) {
             
             int SWIPE_THRESHOLD_VELOCITY = 120;
             try {
               double xDir = e1.getX() - e2.getX();
               double yDir = e1.getY() - e2.getY();

               Log.d("Console","xVel = " + xDir);
               Log.d("Console","yVel = " + yDir);

             if ( xDir > SWIPE_THRESHOLD_VELOCITY) {
                 if( yDir > SWIPE_THRESHOLD_VELOCITY) {
                     //Up-Left swipe
                      maze.keyDown('l');
                 }
                 else  if ( yDir < -SWIPE_THRESHOLD_VELOCITY){
                     //Down-Left swipe
                      maze.keyDown('l');
                 }
                 else{
                     //Left swipe
                     maze.keyDown('l');
                 }

                 return true;
             } else if (xDir < -SWIPE_THRESHOLD_VELOCITY) {

                 if( yDir > SWIPE_THRESHOLD_VELOCITY) {
                     maze.keyDown('r');
                     //Up-Right swipe
                 }
                 else  if ( yDir < -SWIPE_THRESHOLD_VELOCITY){
                     maze.keyDown('r');
                     //Down-Right swipe
                 }
                 else {
                     //Right swipe
                     maze.keyDown('r');
                 }

                 return true;

             }

             if ( yDir < -SWIPE_THRESHOLD_VELOCITY) {
                 //Down swipe
                     maze.keyDown('b');
                 return true;
             }


             if ( yDir > SWIPE_THRESHOLD_VELOCITY) {
                 //Up swipe
                     maze.keyDown('f');
                 return true;
             }
           } catch (Exception e) {
             Log.e("YourActivity", "Error on gestures");
           }

           return false;
     }


     @Override
     public void onLongPress(MotionEvent e) {
             // TODO Auto-generated method stub
             
     }


     @Override
     public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                     float distanceY) {
             // TODO Auto-generated method stub
             return false;
     }


     @Override
     public void onShowPress(MotionEvent e) {
             // TODO Auto-generated method stub
             
     }


     @Override
     public boolean onSingleTapUp(MotionEvent e) {
//           maze.keyDown('f');
             return false;
     }


     @Override
     public boolean onDoubleTap(MotionEvent e) {
             // TODO Auto-generated method stub
             return false;
     }


     @Override
     public boolean onDoubleTapEvent(MotionEvent e) {
             // TODO Auto-generated method stub
             return false;
     }


     @Override
     public boolean onSingleTapConfirmed(MotionEvent e) {
             // TODO Auto-generated method stub
             return false;
     }
	
}
